<template>
  <VDialog @close="handleClose" @save="save" :loading="loading">
    <template #content>
      <div>
        <el-form
          ref="formRef"
          :model="formValues"
          :rules="rules"
          label-width="95px"
          label-position="top"
        >
          <el-form-item label="类型" prop="type">
            <VSelects
              v-model="formValues.type"
              :dataSourse="optionsData?.fund_dispatch_type || []"
              clearable
              class="w-[100%]"
            />
          </el-form-item>
          <el-form-item label="支出渠道" prop="expenditureAccountType">
            <VGroup class="w-[100%]">
              <VSelects
                v-model="formValues.expenditureAccountType"
                :dataSourse="optionsData?.account_type || []"
                placeholder="账号类型"
                clearable
                class="w-[100%]"
                @change="handleAccountType"
              />
              <VSelects
                v-model="formValues.expenditureChannel"
                :dataSourse="optionsData?.channelList || []"
                placeholder="渠道/银行名称"
                class="w-[100%]"
                labelField="channelName"
                valueField="id"
                @change="handleAccountChanne"
              />
            </VGroup>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="账号/卡号" prop="expenditureAccountId">
                <VSelects
                  v-model="formValues.expenditureAccountId"
                  :dataSourse="expenditureAccountOption"
                  clearable
                  class="w-[100%]"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="支出金额" prop="expenditureAmount">
                <VGroup>
                  <el-input-number
                    v-model="formValues.expenditureAmount"
                    clearable
                    :controls="false"
                    placeholder="请输入支出金额"
                    class="w-[100%]"
                    @input="handleExpenditureAmount"
                  />
                  <VSelects
                    v-model="formValues.expenditureCurrency"
                    :dataSourse="optionsData?.currency || []"
                    placeholder="币种"
                    valueField="label"
                    class="w-[100%]"
                  />
                </VGroup>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="收入渠道" prop="incomeAccountType">
            <VGroup class="w-[100%]">
              <VSelects
                v-model="formValues.incomeAccountType"
                :dataSourse="optionsData?.account_type || []"
                placeholder="账号类型"
                clearable
                class="w-[100%]"
                @change="handleAccountType1"
              />
              <VSelects
                v-model="formValues.incomeChannel"
                :dataSourse="optionsData?.channelList || []"
                placeholder="渠道/银行名称"
                class="w-[100%]"
                labelField="channelName"
                valueField="id"
                @change="handleAccountChanne1"
              />
            </VGroup>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="账号/卡号" prop="incomeAccountId">
                <VSelects
                  v-model="formValues.incomeAccountId"
                  :dataSourse="accountOption1"
                  clearable
                  class="w-[100%]"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="收入金额"
                prop="incomeAmount"
                class="custom-form-item"
              >
                <template #label>
                  <div class="flex justify-between">
                    <span class="font-bold ml-[12px]">收入金额</span>
                    <span>汇率: {{ formValues.exchangeRate }}</span>
                  </div>
                </template>
                <VGroup>
                  <el-input-number
                    v-model="formValues.incomeAmount"
                    clearable
                    :controls="false"
                    placeholder="请输入收入金额"
                    class="w-[100%]"
                    @input="handleIncomeAmount"
                  />
                  <VSelects
                    v-model="formValues.incomeCurrency"
                    :dataSourse="optionsData?.currency || []"
                    placeholder="币种"
                    valueField="label"
                    class="w-[100%]"
                  />
                </VGroup>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注说明">
            <el-input v-model="formValues.remark" :rows="2" type="textarea" />
          </el-form-item>
        </el-form>
      </div>
    </template>
  </VDialog>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { getAccountOption } from "@/api/index.js";
import { editCapitalDispatch, addCapitalDispatch } from "../../../api.js";
const props = defineProps({
  data: { type: Object, default: () => {} },
  optionsData: { type: Object, default: () => {} },
});
const { optionsData } = toRefs(props);
const rules = reactive({
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
  expenditureAccountType: [
    { required: true, message: "请选择支出账号类型", trigger: "change" },
  ],
  expenditureAccountId: [
    { required: true, message: "请选择支出账号", trigger: "change" },
  ],
  expenditureAmount: [
    { required: true, message: "请输入支出金额", trigger: "blur" },
  ],
  incomeAccountType: [
    { required: true, message: "请选择收入账号类型", trigger: "change" },
  ],
  incomeAccountId: [
    { required: true, message: "请选择收入账号", trigger: "change" },
  ],
  incomeAmount: [
    { required: true, message: "请输入收入金额", trigger: "blur" },
  ],
});
const emit = defineEmits(["update:modelValue", "close", "refresh"]);
const loading = ref(false);
const formValues = ref({
  id: null,
  type: null,
  expenditureAccountType: null,
  expenditureChannel: null,
  expenditureAccountId: null,
  expenditureAmount: null,
  expenditureCurrency: "CNY",
  expenditureChannelDescribe: null,
  incomeChannelDescribe: null,
  incomeAccountType: null,
  incomeChannel: null,
  incomeAccountId: null,
  incomeAmount: null,
  incomeCurrency: "CNY",
  remark: null,
  exchangeRate: 1.0,
});
const formRef = ref();

watch(
  () => props.data,
  (val) => {
    if (val) {
      for (let key in formValues.value) {
        formValues.value[key] = val[key];
      }
      if (formValues.value.id) {
        getAccountOptionList(
          {
            accountChannelId: formValues.value.expenditureChannel,
            accountType: formValues.value.expenditureAccountType,
          },
          1
        );
        getAccountOptionList(
          {
            accountChannelId: formValues.value.incomeChannel,
            accountType: formValues.value.incomeAccountType,
          },
          2
        );
      }
    }
  }
);
// const exCurrency = ref(0);
// const inCurrency = ref(0);
// const changeCurrency = (val) => {
//   exCurrency.value = val?.value || 0;
//   if (inCurrency.value && val.value) {
//     formValues.value.exchangeRate = parseFloat(
//       (inCurrency.value / val.value).toFixed(4)
//     );
//   } else {
//     formValues.value.exchangeRate = 1.0;
//   }
// };
// const changeInCurrency = (val) => {
//   inCurrency.value = val?.value || 0;
//   if (exCurrency.value && val.value) {
//     formValues.value.exchangeRate = parseFloat(
//       (val.value / exCurrency.value).toFixed(4)
//     );
//   } else {
//     formValues.value.exchangeRate = 1.0;
//   }
// };
const handleExpenditureAmount = (val) => {
  if (val && formValues.value.incomeAmount) {
    formValues.value.exchangeRate = parseFloat(
      (val / formValues.value.incomeAmount).toFixed(4)
    );
  } else {
    formValues.value.exchangeRate = 1.0;
  }
};
const handleIncomeAmount = (val) => {
  if (val && formValues.value.expenditureAmount) {
    formValues.value.exchangeRate = parseFloat(
      (formValues.value.expenditureAmount / val).toFixed(4)
    );
  } else {
    formValues.value.exchangeRate = 1.0;
  }
};
const save = async () => {
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        loading.value = true;
        const { code, message } = await (formValues.value?.id
          ? editCapitalDispatch
          : addCapitalDispatch)(formValues.value);
        if (code !== 200) return;
        ElMessage.success(formValues.value?.id ? "编辑成功" : "添加成功");
        handleClose(true);
      } catch (error) {
      } finally {
        loading.value = false;
      }
    }
  });
};
const expenditureAccountOption = ref([]);
const accountOption1 = ref([]);
const handleAccountChanne = (val) => {
  if (val) {
    let obj = optionsData?.value?.channelList?.find((item) => item.id == val);
    formValues.value.expenditureChannelDescribe = obj.channelName;
  } else {
    formValues.value.expenditureChannelDescribe = null;
  }
  if (!(val && formValues.value.expenditureAccountType)) {
    formValues.value.expenditureAccountId = null;
    expenditureAccountOption.value = [];
    return;
  }
  getAccountOptionList(
    {
      accountChannelId: val,
      accountType: formValues.value.expenditureAccountType,
    },
    1
  );
};
const handleAccountType = (val) => {
  if (!(val && formValues.value.expenditureChannel)) {
    formValues.value.expenditureAccountId = null;
    expenditureAccountOption.value = [];
    return;
  }
  getAccountOptionList(
    {
      accountChannelId: formValues.value.expenditureChannel,
      accountType: val,
    },
    1
  );
};
const handleAccountChanne1 = (val) => {
  if (val) {
    let obj = optionsData?.value?.channelList?.find((item) => item.id == val);
    formValues.value.incomeChannelDescribe = obj.channelName;
  } else {
    formValues.value.incomeChannelDescribe = null;
  }
  if (!(val && formValues.value.incomeAccountType)) {
    formValues.value.incomeAccountId = null;
    accountOption1.value = [];
    return;
  }
  getAccountOptionList(
    {
      accountChannelId: val,
      accountType: formValues.value.incomeAccountType,
    },
    2
  );
};
const handleAccountType1 = (val) => {
  if (!(val && formValues.value.incomeChannel)) {
    formValues.value.incomeAccountId = null;
    accountOption1.value = [];
    return;
  }
  getAccountOptionList(
    {
      accountChannelId: formValues.value.incomeChannel,
      accountType: val,
    },
    2
  );
};
const getAccountOptionList = async (params, ind) => {
  const { data } = await getAccountOption(params);
  data?.forEach((item) => {
    item.value = item.value.toString();
  });
  if (ind == 1) {
    expenditureAccountOption.value = data || [];
  } else {
    accountOption1.value = data || [];
  }
};
const handleClose = async (refresh) => {
  formValues.value = {
    id: null,
  type: null,
  expenditureAccountType: null,
  expenditureChannel: null,
  expenditureAccountId: null,
  expenditureAmount: null,
  expenditureCurrency: "CNY",
  expenditureChannelDescribe: null,
  incomeChannelDescribe: null,
  incomeAccountType: null,
  incomeChannel: null,
  incomeAccountId: null,
  incomeAmount: null,
  incomeCurrency: "CNY",
  remark: null,
  exchangeRate: 1.0,
  };
  formRef.value.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
<style scoped lang="scss">
.custom-form-item {
  :deep(.el-form-item__label) {
    position: relative;
    &::before {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
  }
}
</style>
